const {ccclass, property} = cc._decorator;

@ccclass
export default class GameOver extends cc.Component {

    /**血流成河或血战到底的结束后的UI的容器 */
    gameOver: cc.Node = null;
    /**平局图片的node节点 */
    pingJu:cc.Node = null;
    /**赢了图片的node节点 */
    win: cc.Node = null;
    /**输了图片的node节点 */
    lose: cc.Node = null;
    /**游戏战绩的容器 */
    gameResult: cc.Node = null;

    seats: cc.viewdata[] = [];

    /**游戏是否完全结束 */
    isGameEnd = false;
    onLoad() {
        if(!cc.vv){
            console.log('GameOver->onLoad->cc.vv没有值', cc.vv.logStyle);
            return;
        }
        if(!cc.vv.gameNetMgr.conf){
            console.log('GameOver->onLoad->cc.vv.gameNetMgr.conf没有值', cc.vv.logStyle);
            return;
        }


        if(cc.vv.gameNetMgr.conf.type == 'xzdd'){
            this.gameOver = this.node.getChildByName('game_over');
        }
        else{
            this.gameOver = this.node.getChildByName('game_over_xlch');
        }
        this.gameOver.active = false;

        this.pingJu = this.gameOver.getChildByName('pingju');
        this.win = this.gameOver.getChildByName('win');
        this.lose = this.gameOver.getChildByName('lose');
        
        this.gameResult = this.node.getChildByName('game_result');

        let wanfa = this.gameOver.getChildByName('wanfa').getComponent(cc.Label);
        wanfa.string = cc.vv.gameNetMgr.getWanfa();

        const listRoot = this.gameOver.getChildByName('result_list');
        // 初始化详细的牌的结果
        for(let i = 1; i <= 4; i++){
            let s = 's' + i;
            let sn = listRoot.getChildByName(s);
            let viewdata: cc.viewdata = {};
            viewdata.userName = sn.getChildByName('username').getComponent(cc.Label);
            viewdata.reason = sn.getChildByName('reason').getComponent(cc.Label);
            let f = sn.getChildByName('fan');
            if(f){
                viewdata.fan = f.getComponent(cc.Label);
            }
            viewdata.score = sn.getChildByName('score').getComponent(cc.Label);
            viewdata.hu = sn.getChildByName('hu');
            viewdata.mahjongs = sn.getChildByName('pai');
            viewdata.zhuang = sn.getChildByName('zhuang');
            viewdata.huPai = sn.getChildByName('hupai');
            viewdata.pengAndGang = [];
            this.seats.push(viewdata);

            /**xzdd的准备的节点 */
            const xzddReadyBtn = cc.find('Canvas/game_over/btnReady');
            /**xlch的准备的节点 */
            const xlchReadyBtn = cc.find('Canvas/game_over_xlch/btnReady');
            // 准备按钮添加点击事件
            cc.vv.utils.addClickEvent(xzddReadyBtn, this.node, 'GameOver', 'onBtnReadyClicked')
            cc.vv.utils.addClickEvent(xlchReadyBtn, this.node, 'GameOver', 'onBtnReadyClicked')

            this.node.on(cc.vv.game_event_map.GAME_OVER, (data) => {
                this.onGameOver(data.detail);
            });

            this.node.on(cc.vv.game_event_map.GAME_END, (data) => {
                this.isGameEnd = true;
            });
        }
    }


    /**游戏结束后处理的逻辑 */
    onGameOver(data: cc.gameOverData[]){
        if(cc.vv.gameNetMgr.conf){
            const type = cc.vv.gameNetMgr.conf.type;
            if(type == 'xzdd'){
                this.onGameOver_XZDD(data);
            }
            else{
                this.onGameOver_XLCH(data);
            }
        }
    }

    /**xzdd的玩法结束后 */
    onGameOver_XZDD(data: cc.gameOverData[]){
        if(data.length == 0){
            this.gameResult.active = true;
            return;
        }

        this.gameOver.active = true;
        this.pingJu.active = false;
        this.win.active = false;
        this.lose.active = false;

        const myScore = data[cc.vv.gameNetMgr.seatIndex].score;
        if(myScore > 0){
            this.win.active = true;
        }
        else if(myScore < 0){
            this.lose.active = true;
        }
        else{
            this.pingJu.active = true;
        }

        // 显示玩家信息
        for(let i = 0; i < 4; i++){
            const seatView = this.seats[i];
            const userData = data[i];
            let hued = false;
            const numOfGangs = userData.anGangs.length + userData.wanGangs.length + userData.dianGangs.length;
            const numOfGen = userData.numOfGen;
            const actionArr = [];
            let is7pairs = false;
            let isChaDaJiao = false;

            const pushActionArr = () => {
                switch (userData.pattern) {
                    case '7pairs':
                        actionArr.push('七对');
                        break;
                    case '17pairs':
                        actionArr.push('七龙对');
                        break;
                    case 'j7pairs':
                        actionArr.push('将七对');
                        break;
                    case 'duidui':
                        actionArr.push('碰碰胡');
                        break;
                    case 'jiangdui':
                        actionArr.push('将对');
                        break;
                }
                hued = true;
            };

            userData.actions.forEach((action) => {
                switch(action.type){
                    case 'zimo':
                        pushActionArr();
                        actionArr.push('自摸');
                        break;
                    case 'ganghua':
                        pushActionArr();
                        actionArr.push('杠上花');
                        break;
                    case 'dianganghua':
                        pushActionArr();
                        actionArr.push('点杠花');
                        break;
                    case 'hu':
                        pushActionArr();
                        break;
                    case 'gangpaohu':
                        pushActionArr();
                        actionArr.push('杠炮胡');
                        break;
                    case 'qiangganghu':
                        pushActionArr();
                        actionArr.push('抢杠胡');
                        break;
                    case 'chadajiao':
                        isChaDaJiao = true;
                        break;
                    case 'fangpao':
                        actionArr.push('放炮');
                        break;
                    case 'angang':
                        actionArr.push('暗杠');
                        break;
                    case 'diangang':
                        actionArr.push('明杠');
                        break;
                    case 'wangang':
                        actionArr.push('弯杠');
                        break;
                    case 'fanggang':
                        actionArr.push('放杠');
                        break;
                    case 'zhuanshougang':
                        actionArr.push('转手杠');
                        break;
                    case 'beiqianggang':
                        actionArr.push('被抢杠');
                        break;
                    case 'beichadajiao':
                        actionArr.push('被查叫');
                        break;
                }
            });

            if(hued){
                if(userData.qingYiSe){
                    actionArr.push('清一色');
                }
                if(userData.menQing){
                    actionArr.push('门清');
                }
                if(userData.zhongZhang){
                    actionArr.push('中张');
                }
                if(userData.jinGouHu){
                    actionArr.push('金钩胡');
                }
                if(userData.haiDiHu){
                    actionArr.push('海底胡');
                }
                if(userData.tianHu){
                    actionArr.push('天胡');
                }
                if(userData.diHu){
                    actionArr.push('地胡');
                }
                if(numOfGen >0){
                    actionArr.push('根x' + numOfGen);
                }
                if(isChaDaJiao){
                    actionArr.push('查大叫');
                }
            }

            for(let j = 0; j < 3; j++){
                seatView.hu.children[j].active = false;
            }

            if(userData.huOrder >= 0){
                seatView.hu.children[userData.huOrder].active = false;
            }

            seatView.userName.string = cc.vv.gameNetMgr.seats[i].name;
            seatView.zhuang.active = cc.vv.gameNetMgr.button == i;
            seatView.reason.string = actionArr.join('、');

            let fan = 0;
            if(hued){
                fan = userData.fan;
            }
            seatView.fan.string = fan + '番';

            if(userData.score > 0){
                seatView.score.string = '+' + userData.score;
            }
            else{
                seatView.score.string = userData.score;
            }

            // 胡牌不参与排序
            let huPai = -1;
            if(hued){
                huPai = userData.holds.pop();
            }
            cc.vv.mahjongmgr.sortMJ(userData.holds, userData.dingQue);
            if(hued){
                userData.holds.push(huPai);
            }

            // 隐藏所有牌
            seatView.mahjongs.children.forEach((child) => {
                child.active = false;
            });

            // 显示相关的牌
            const lackingNum = (userData.pengs.length + numOfGangs) * 3;
            userData.holds.forEach((pai, k) => {
                const n = seatView.mahjongs.children[k + lackingNum];
                n.active = true;
                const sprite = n.getComponent(cc.Sprite);
                sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.M, pai);
            });

            seatView.pengAndGang.forEach((pengAndGang) => {
                pengAndGang.active = false;
            });

            let index = 0;

            // 初始化杠牌
            userData.anGangs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'angang');
                index++;
            });
            userData.dianGangs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'diangang');
                index++;
            });
            userData.wanGangs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'wangang');
                index++;
            });
            // 初始化碰牌
            userData.pengs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'peng');
                index++;
            });

        }
    }

    onGameOver_XLCH(data: cc.gameOverData[]){
        if (data.length == 0) {
            this.gameResult.active = true;
            return;
        }

        this.gameOver.active = false;
        this.pingJu.active = false;
        this.win.active = false;
        this.lose.active = false;

        const myScore = data[cc.vv.gameNetMgr.seatIndex].score;
        if (myScore > 0) {
            this.win.active = true;
        }
        else if (myScore < 0) {
            this.lose.active = true;
        }
        else {
            this.pingJu.active = true;
        }

        // 显示玩家信息
        for(let i = 0; i < 4; i++){
            const seatView = this.seats[i];
            const userData = data[i];
            let hued = false;
            const actionArr = [];
            let is7pairs = false;
            let isChaDaJiao = false;
            const huPaiRoot = seatView.huPai;

            huPaiRoot.children.forEach((child) => {
                child.active = false;
            });

            let hi = 0;
            userData.huInfo.forEach((info) => {
                hued = hued || info.isHuPai;
                if(info.isHuPai){
                    if(hi < huPaiRoot.childrenCount){
                        const huPaiView = huPaiRoot.children[hi];
                        huPaiView.active = true;
                        huPaiView.getComponent(cc.Sprite).spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.B, info.pai);
                        hi++;
                    }
                }

                let str = '';
                let sep = '';
                let dataSeat = userData;
                if(!info.isHuPai){
                    switch(info.action){
                        case 'fangpao':
                            str = '放炮';
                            break;
                        case 'gangpao':
                            str = '杠上炮';
                            break;
                        case 'beiqianggang':
                            str = '被抢杠';
                            break;
                        default:
                            str = '被查大叫';
                            break;
                    }
                    dataSeat = data[info.target];
                    info = dataSeat.huInfo[info.index];
                }
                else{
                    switch(info.action){
                        case 'hu':
                            str = '接炮胡';
                            break;
                        case 'zimo':
                            str = '自摸';
                            break;
                        case 'ganghua':
                            str = '杠上花';
                            break;
                        case 'dianganghua':
                            str = '点杠花';
                            break;
                        case 'gangpaohu':
                            str = '杠炮胡';
                            break;
                        case 'qiangganghu':
                            str = '抢杠胡';
                            break;
                        case 'chadajiao':
                            str = '查大叫';
                            break;
                    }
                }

                str += '(';
                switch(info.pattern){
                    case '7pairs':
                        str += '七对';
                        sep = '、';
                        break;
                    case 'l7pairs':
                        str += '龙七对';
                        sep = '、';
                        break;
                    case 'j7pairs':
                        str += '将七对';
                        sep = '、';
                        break;
                    case 'duidui':
                        str += '碰碰胡';
                        sep = '、';
                        break;
                    case 'jiangdui':
                        str += '将对';
                        sep = '、';
                        break;
                }
                if(info.haiDiHu){
                    str += sep + '海底胡';
                    sep = '、';
                }
                if(info.tianHu){
                    str += sep + '天胡';
                    sep = '、';
                }
                if(info.diHu){
                    str += sep + '地胡';
                    sep = '、';
                }
                if(dataSeat.qingYiSe){
                    str += sep + '清一色';
                    sep = '、';
                }
                if(dataSeat.menQing){
                    str += sep + '门清';
                    sep = '、';
                }
                if(dataSeat.jinGouHu){
                    str += sep + '金钩胡';
                    sep = '、';
                }
                if(dataSeat.zhongZhang){
                    str += sep + '中张';
                    sep = '、';
                }
                if(info.numOfGen > 0){
                    str += sep + '根x' + info.numOfGen;
                    sep = '、';
                }

                if(sep == ''){
                    str += '平胡';
                }
                str += '、' + info.fan + '番)';
                actionArr.push(str);
            });

            seatView.hu.active = hued;
            
            if (userData.anGangs.length){
                actionArr.push('暗杠x' + userData.anGangs.length);
            }
            if (userData.dianGangs.length){
                actionArr.push('明杠x' + userData.dianGangs.length);
            }
            if (userData.wanGangs.length){
                actionArr.push('巴杠x' + userData.wanGangs.length);
            }

            seatView.userName.string = cc.vv.gameNetMgr.seats[i].name;
            seatView.zhuang.active = cc.vv.gameNetMgr.button == i;
            seatView.reason.string = actionArr.join('、');

            if(userData.score > 0){
                seatView.score.string = '+' + userData.score;
            }
            else{
                seatView.score.string = userData.score;
            }

            // 隐藏所有牌
            seatView.mahjongs.children.forEach((child) => {
                child.active = false;
            });

            cc.vv.mahjongmgr.sortMJ(userData.holds, userData.dingQue);

            const numOfGangs = userData.anGangs.length + userData.wanGangs.length + userData.dianGangs.length;
            const lackingNum = (userData.pengs.length + numOfGangs) * 3;
            // 显示相关的牌
            userData.holds.forEach((pai, index) => {
                const n = seatView.mahjongs.children[index + lackingNum];
                n.active = true;
                const sprite = n.getComponent(cc.Sprite);
                sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.M, pai);
            });

            // 隐藏所有杠牌
            seatView.pengAndGang.forEach((pengAndGang) => {
                pengAndGang.active = false;
            });

            // 显示相关的杠牌
            let index = 0;
            userData.anGangs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'angang');
                index++;
            });
            userData.dianGangs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'diangang');
                index++;
            });
            userData.wanGangs.forEach((mjId) => {
                this.initPengAndGangs(seatView, index, mjId, 'wangang');
                index++;
            });

            // 显示相关的碰牌
            if(userData.pengs){
                userData.pengs.forEach((mjId) => {
                    this.initPengAndGangs(seatView, index, mjId, 'wangang');
                    index++;
                });
            }
        }
    }

    initPengAndGangs(seatView: cc.viewdata, index, mjId, flag){
        let pgRoot: cc.Node = null;
        if(seatView.pengAndGang.length <= index){
            pgRoot = cc.instantiate(cc.vv.mahjongmgr.pengPrefabSelf);
            seatView.pengAndGang.push(pgRoot);
            seatView.mahjongs.addChild(pgRoot);
        }
        else{
            pgRoot = seatView.pengAndGang[index];
            pgRoot.active = true;
        }

        const sprites = pgRoot.getComponentsInChildren(cc.Sprite);
        sprites.forEach((sprite) => {
            if(sprite.node.name == 'gang'){
                const isGang = flag != 'peng';
                sprite.node.active = isGang;
                sprite.node.scaleX = 1.0;
                sprite.node.scaleY = 1.0;
                if(flag == 'angang'){
                    sprite.spriteFrame = cc.vv.mahjongmgr.getEmptySpriteFrame(cc.vv.directions.myself);
                    sprite.node.scaleX = 1.4;
                    sprite.node.scaleY = 1.4;
                }
                else{
                    sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.B, mjId);
                }
            }
            else{
                sprite.spriteFrame = cc.vv.mahjongmgr.getSpriteFrameByMJID(cc.vv.preAtlasString.B, mjId);
            }
        });
        pgRoot.x = index * 55 * 3 + index * 10;
    }


    /**结束界面上的准备按钮的点击事件 */
    onBtnReadyClicked(){
        if(this.isGameEnd){
            this.gameResult.active = true;
        }
        else{
            cc.vv.net.send(cc.vv.game_event_map.READY);
        }
        this.gameOver.active = false;
    }

}
